﻿using UnityEngine;
using System.Collections;
using DG.Tweening;
using UnityEngine.EventSystems;
using System.Collections.Generic;
/// <summary>
/// 超市主控制器
/// </summary>
public class SuperMarketGame : MonoSingleton<SuperMarketGame>
{
    [SerializeField]
    public Camera superCamera;
    [SerializeField]
    Camera shaomaCamera;
    [SerializeField]
    Camera shouyinCamera;

    [SerializeField]
    GameType _currentGameType = GameType.Cleanliness;

    //购物车
    Transform shoppingCar;
    public Transform downPoint;
    public Transform putPoint;
    /*public Transform putPoint1;
    public Transform putPoint2;
    public Transform putPoint3;*/
    //记录商品放入购物车时人物的旋转（用来解决面片透明）
    public Dictionary<int, float> putPointCarRotateDic = new Dictionary<int, float>();

    public GameType CurrentGameType
    {
        get { return _currentGameType; }
        set { _currentGameType = value; }
    }

    /// <summary>
    /// 场景是否拖拽 
    /// </summary>
    [HideInInspector]
    public bool isCanDragScene = false;
    public float smoothing = 5f;

    private float roleRotate = 0.022f;
    public float RoleRotate
    {
        get; set;
    }
    //购物过程中是否开启检测玩家有无操作(出引导)
    private bool isCheckOperate = false;
    //3秒检测
    public float heartTimeCheck = 6f;
    public float guidTotalCount = 0f;
    public bool IsCheckOperate
    {
        get
        {
            return isCheckOperate;
        }
        set
        {
            isCheckOperate = value;
            if (!isCheckOperate)
            {
                guidTotalCount = 0;
            }
        }
    }

    /// <summary>  
    /// 第一次按下的位置  
    /// </summary>  
    private Vector3 firstMousePos = Vector3.zero;

    //3D场景
    GameObject sceneObject;
    //乐迪
    GameObject lediObject;
    Animator lediAnim;
    public Vector3 lediPos = new Vector3(-1.356f, 0, -2.501f);
    //角色
    //当前角色（记录上次使用角色）
    private RoleType curRoleType;
    public RoleType CurRoleType
    {
        get; set;
    }
    //游戏进行次数
    public int gameCount = 0;
    //参与小游戏次数
    public int cleanGameCount = 0;
    public int addgoodsGameCount = 0;
    public int sortoutCarGameCount = 0;

    //主角
    GameObject roleObject;
    //扫码机器    
    GameObject scanCodeObject;
    //收银台
    GameObject cashRegisterObject;

    /* [RuntimeInitializeOnLoadMethodAttribute]
     static void OnInit()
     {

         if (Instance == null)
         {
             GameObject go = new GameObject("SuperMarketGame");
             go.AddComponent<SuperMarketGame>();
             GameObject.DontDestroyOnLoad(Instance);
         }
     }*/
    public SuperMarketSoundCtrl soundCtrl;

    private Vector3 orgMainCamPos;
    private Quaternion orgMainCamRota;

    //检测关闭ShopList弹窗UI，5秒不动自动消息  是否开启检测
    private bool isCheckShopPanel = false;
    public bool IsCheckShopPanel
    {
        get;
        set;
    }

    float shopPanelOpenTime = 5f;

    /// <summary>
    /// 是否第一次游戏 引导使用
    /// </summary>
    public bool isFirstPlay;
    /// <summary>
    /// 购物区是否需要引导手指  1 = true 0 false
    /// </summary>
    public bool guidHand = true;
    /// <summary>
    ///  购物区是否需要引导走路  1 = true 0 false
    /// </summary>
    public bool guidWay = true;
    protected override void Awake()
    {
        //base.Awake();        

        Transform cam = GameObject.Find("cams").transform;
        superCamera = cam.Find("camera_main").GetComponent<Camera>();
        shaomaCamera = cam.Find("camera_shaoma").GetComponent<Camera>();
        shouyinCamera = cam.Find("camera_shouyin").GetComponent<Camera>();
        //0.5  2.45  9.39  
        orgMainCamPos = superCamera.transform.position;  // y 1.57 z 5
        orgMainCamRota = superCamera.transform.rotation;

        soundCtrl = gameObject.AddComponent<SuperMarketSoundCtrl>();

        string datas = PlayerPrefs.GetString("supermarket_first");
        if (string.IsNullOrEmpty(datas))
        {
            PlayerPrefs.SetString("supermarket_first", "1");
            isFirstPlay = true;
        }
        else
        {
            isFirstPlay = false;
        }
        Debug.Log(isFirstPlay.ToString() + " isFirstPlay  ============= ");

        InitGameObject();

    }
    // Use this for initialization
    void Start()
    {
        //===================== mjbTest
        //SuperMarketController.Instance.OpenView();
        Input.multiTouchEnabled = false;


        guidHand = true;
        guidWay = true;
    }

    public void InitGameObject()
    {
        superCamera.transform.position = orgMainCamPos;
        //初始化场景
        if (sceneObject == null)
        {
            sceneObject = Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.SceneObject));
        }
        //初始化乐迪
        if (lediObject == null)
        {
            lediObject = Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.LediObject));
            lediObject.transform.position = lediPos;
            lediObject.transform.localScale = new Vector3(0.012f, 0.012f, 0.012f);
            lediAnim = lediObject.transform.GetChild(0).GetComponent<Animator>();
            RuntimeAnimatorController con = ResourceManager.Instance.GetResource(SuperMarketResPath.LediAnimObject, typeof(RuntimeAnimatorController), enResourceType.Prefab, false, false).m_content as RuntimeAnimatorController;
            lediAnim.runtimeAnimatorController = con;
            lediAnim.Rebind();

            lediObject.GetComponent<BoxCollider>().enabled = false;
        }
        //乐迪超市，满载而归。  乐迪：“营业之前先整理，用整洁的环境迎接客人到来。”
        //SetLediAnim("sayhello1");
        System.Action action = () =>
        {
            if (gameCount > 5 || gameCount == 0)//   ====== mjbTest
            {
                //SetLediAnim("sayhello2");
                soundCtrl.PlayLeDiVoiceAnimation(SuperMarketResPath.Sound_404050102, () =>
                {
                    /*
           * 随机小游戏 
           当玩家重复购物5-6次后，客人到来前，随机出超市整理小游戏（3个），完成整理游戏后，客人到来，重复购物。
                   乐迪（叙述的）：“哎呀，超市有点脏了”
                  “购物车有点乱了，去整理整理吧。”
                  “货柜上的货卖光了，我们要去补充下货物了哦。”
           */
                    isCanDragScene = false;
                    MarketMainSceneCtrl.Instance.isCanMove = false;
                    int random = Random.Range(0, 3);
                    // ====== mjbTest
                    //random = 1;
                    Debug.Log(" 随机的小游戏 random === " + random);
                    CurrentGameType = (GameType)random;
                    GameObject go;
                    switch ((GameType)random)
                    {
                        case GameType.Cleanliness:
                            cleanGameCount++;
                            TransitionManager.Instance.StartTransition(() => { }, () =>
                            {
                                go = Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.CleanObject));
                                CleanMarketController cmc = go.GetComponent<CleanMarketController>();
                                if (cmc == null)
                                    cmc = go.AddComponent<CleanMarketController>();
                                cmc.StartGame();
                            }, TransitionType.Logo);
                            break;
                        case GameType.PlaceGoods:
                            addgoodsGameCount++;
                            TransitionManager.Instance.StartTransition(() => { }, () =>
                            {
                                go = Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.AddGoodsObject));
                                AddGoodsController agc = go.GetComponent<AddGoodsController>();
                                if (agc == null)
                                    agc = go.AddComponent<AddGoodsController>();
                                if (gameCount > 5)
                                    agc.isClearGoods = true;
                                agc.StartGame();
                            }, TransitionType.Logo);
                            break;
                        case GameType.ShoppingCart:
                            sortoutCarGameCount++;
                            TransitionManager.Instance.StartTransition(() => { }, () =>
                            {
                                go = Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.ShopCarObject));
                                SortoutCarController scc = go.GetComponent<SortoutCarController>();
                                if (scc == null)
                                    scc = go.AddComponent<SortoutCarController>();
                                scc.StartGame();
                            }, TransitionType.Logo);
                            break;
                    }
                });

            }
            else
            {
                //isCanDragScene = true;
                //正常购物流程
                //MarketMainSceneCtrl.Instance.isCanMove = true;                
                //角色初始化
                if (roleObject == null)
                {
                    if (CurRoleType == 0 || CurRoleType == RoleType.nuowa)
                        CurRoleType = RoleType.ajiasi;
                    else if (CurRoleType == RoleType.ajiasi)
                        CurRoleType = RoleType.aisha;
                    else if (CurRoleType == RoleType.aisha)
                        CurRoleType = RoleType.nuowa;

                    //mhbTest
                    //CurRoleType = RoleType.aisha;
                    //Debug.Log(SuperMarketResPath.PREFAB_DIR + CurRoleType.ToString());
                    roleObject = Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.PREFAB_DIR + CurRoleType.ToString()));
                    roleObject.AddComponent<RoleInSuperMarketCtrl>();
                }
                //TO DO 摆放货架
                PlaceGoods.Instance.Place();
                soundCtrl.PlayLeDiVoiceAnimation(SuperMarketResPath.Sound_404050108);
                //SuperMarketGame.Instance.SetLediAnim("sayhello1");
                MarketMainSceneCtrl.Instance.OpenTheDoor(() =>
                {
                    RoleInSuperMarketCtrl.Instance.WalkInSide();
                });
            }
        };
        Debug.Log("  gameCount ==== " + gameCount);
        if (gameCount == 0)
            soundCtrl.PlayLeDiVoiceAnimation(SuperMarketResPath.Sound_404050101, action); 
        else
            action();
    }
    /// <summary>
    /// 购物引导  1, 如果是第一次就立刻引导 加上UI引导 ，不是第一次无操作间隔8秒引导（UI  点击，当点击完成，再出滑动）
    /// </summary>
    public void GuidBuyGoods()
    {

        if (isFirstPlay)
        {
            //播放声音
            //404050350
            soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050350);
            ShoppingListController.Instance.EnableGuid(true);
        }
        else
        {
            SuperMarketGame.Instance.IsCheckOperate = true;
        }
    }
    private void Update()
    {
        if (!guidHand && !guidWay)
        {
            IsCheckOperate = false;
        }
        if (IsCheckOperate)
        {
            guidTotalCount += Time.deltaTime;
            if (guidTotalCount >= heartTimeCheck)
            {
                Debug.Log("===未操作时间戳.===" + Time.realtimeSinceStartup);
                guidTotalCount = 0;
                //引导手指或者路径            
                if (guidHand)
                {
                    //手指坐标     
                    if (!MarketMainSceneCtrl.Instance.handClick.gameObject.activeSelf)
                    {
                        MarketMainSceneCtrl.Instance.PlayBuyAreaHandTween(PlaceGoods.Instance.GetGuidPosition());
                        if (isFirstPlay)
                            SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050348);
                    }
                }
                else if (guidHand == false && guidWay == true)
                {
                    if (!ShoppingListController.Instance.WayPointState())
                    {
                        WayPointEnable(true);
                        if (isFirstPlay)
                            SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050349);
                    }
                }
            }
            if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
            {
                //ShoppingListController.Instance.WayPointEnable(false);
                guidTotalCount = 0;
            }
        }

        if (IsCheckShopPanel)
        {
            shopPanelOpenTime -= Time.deltaTime;
            if (shopPanelOpenTime <= 0)
            {
                ShoppingListController.Instance.OnBgClick(null);
                shopPanelOpenTime = 5f;
            }
        }
        /*else if (Input.GetKeyDown(KeyCode.Keypad0))
            lediAnim.CrossFade("sayhello1", 0.2f);
        else if (Input.GetKeyDown(KeyCode.Keypad1))
            lediAnim.CrossFade("sayhello2", 0.2f);
        else if (Input.GetKeyDown(KeyCode.Keypad9))
            lediAnim.CrossFade("inspire_ledi_01", 0.2f);
        else if (Input.GetKeyDown(KeyCode.Keypad3))
            MarketMainSceneCtrl.Instance.OpenTheDoor(); 
        else if (Input.GetKeyDown(KeyCode.Keypad4))
            MarketMainSceneCtrl.Instance.CloseTheDoor();*/
    }

    // Update is called once per frame
    //避免没有执行 GetMouseButtonDown  直接执行GetMouseButton（商品拖拽）
    bool isCameraDrag = false;
    void LateUpdate()
    {
        //是否点击UI
        if (isCanDragScene)
        {
            if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
            {
#if !UNITY_EDITOR && (UNITY_IOS || UNITY_ANDROID)
                if (UnityEngine.EventSystems.EventSystem.current!=null && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
                if (UnityEngine.EventSystems.EventSystem.current != null && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
#endif
                {
                    //Debug.LogError("当前触摸在UI上");
                    isCameraDrag = false;
                }
                else
                {
                    //Debug.LogError("当前没有触摸在UI上 === ");
                    firstMousePos = Input.mousePosition;
                    isCameraDrag = true;
                }
                //Debug.Log("点击 === "+ firstMousePos);
            }
            else if (Input.GetMouseButton(0) && firstMousePos != Vector3.zero && isCameraDrag)
            {
                //Debug.Log("firstMousePos === " + firstMousePos + "   , Input.mousePosition === " + Input.mousePosition);
                if (Mathf.Abs(firstMousePos.x - Input.mousePosition.x) > 8f) //Vector3.Distance(firstMousePos, Input.mousePosition)
                {
                    //Debug.Log("  Input.GetMouseButton(0) ===  ");
                    float endValue = 0;
                    //roleRotate = -90f;
                    if (Input.mousePosition.x < firstMousePos.x)
                    {
                        endValue = 1f;//(superCamera.transform.position.x + 1.2f);
                        //Debug.Log("向左拖拽  响应向右事件");
                        RoleRotate = Mathf.Abs(roleObject.transform.localScale.z) * -1;//0.022f;
                    }
                    else
                    {
                        endValue = -1f; //(superCamera.transform.position.x - 1.2f);
                        RoleRotate = Mathf.Abs(roleObject.transform.localScale.z);
                        //Debug.Log("向右拖拽 响应向左事件");
                    }
                    //边界值
                    //endValue = Mathf.Clamp(endValue, -26.06f, -5.3f);//0.5f  -14.19
                    //superCamera.transform.DOMoveX(endValue, 0.3f).OnComplete(()=> {});//.SetEase(Ease.Linear);
                    //Vector3 target = new Vector3(endValue, superCamera.transform.position.y, superCamera.transform.position.z);
                    //Debug.Log(target);
                    //if (Vector3.Distance(superCamera.transform.position, target) >= 0.05f)
                    //{
                    //Debug.Log(target +"  === target");
                    if ((superCamera.transform.position + new Vector3(Time.deltaTime * smoothing * endValue, 0f, 0f)).x >= -5.3f)
                        superCamera.transform.position = new Vector3(-5.3f, superCamera.transform.position.y, superCamera.transform.position.z);
                    else if ((superCamera.transform.position + new Vector3(Time.deltaTime * smoothing * endValue, 0f, 0f)).x <= -26.06f)
                        superCamera.transform.position = new Vector3(-26.06f, superCamera.transform.position.y, superCamera.transform.position.z);
                    else
                        superCamera.transform.position += new Vector3(Time.deltaTime * smoothing * endValue, 0f, 0f);
                    ShoppingListController.Instance.lastType = 0;
                        //superCamera.transform.position = Vector3.MoveTowards(superCamera.transform.position, target, Time.deltaTime * smoothing);
                        if (RoleInSuperMarketCtrl.Instance.isFollowCam && !MarketMainSceneCtrl.Instance.isShakeCar)
                        {
                            //使人物跟随摄像机移动
                            RoleInSuperMarketCtrl.Instance.RoleFollow(true, superCamera.transform.position.x, RoleRotate, smoothing);
                            if (guidWay)
                            {
                                Debug.Log(guidWay.ToString() + "  ===== guidWay");
                                guidWay = false;
                                WayPointEnable(false);
                                AudioManager.Instance.StopSound(AudioManager.Instance.GetAudioClip(SuperMarketResPath.Sound_404050349));
                            }
                        }
                    //}
                    /*if (superCamera.transform.position.x >= -5.3f)
                        superCamera.transform.position = new Vector3(-5.3f, superCamera.transform.position.y, superCamera.transform.position.z);
                    else if(superCamera.transform.position.x <= -26.06f)
                        superCamera.transform.position = new Vector3(-26.06f, superCamera.transform.position.y, superCamera.transform.position.z);*/

                    firstMousePos = Input.mousePosition;

                    /*if (MarketMainSceneCtrl.Instance.isShakeCar)
                    {
                        //提醒选择购物车
                        SetLediAnim("sayhello2");
                    }          */
                }

            }
            else if (Input.GetMouseButtonUp(0) && isCameraDrag)
            {
                isCameraDrag = false;
                //Debug.Log(RoleInSuperMarketCtrl.Instance.IsFinishPlayAniMod.ToString());
                if (RoleInSuperMarketCtrl.Instance.isFollowCam && !MarketMainSceneCtrl.Instance.isShakeCar && isCanDragScene)
                    SetRoleAnim(3);
            }
        }
        else if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
        {
            if (MarketMainSceneCtrl.Instance.isShakeCar)
            {
                //提醒选择购物车
                //Debug.LogError("11111 isShakeCar ==== ");
                MarketMainSceneCtrl.Instance.timeCount = 0;
                SuperMarketGame.Instance.soundCtrl.PlayLeDiVoiceAnimation(SuperMarketResPath.Sound_404050109);
            }
        }
    }
    public void MoveMainCamera(float targetPosition, System.Action callback = null, float targetPosY = 0, float targetPosZ = 0, float during = 0.3f)
    {
        if (targetPosY != 0 && targetPosZ != 0)
        {
            superCamera.transform.DOMove(new Vector3(targetPosition, targetPosY, targetPosZ), during).SetEase(Ease.Linear).OnComplete(() =>
            {
                if (callback != null)
                    callback();
            });
        }
        else
        {
            superCamera.transform.DOMoveX(targetPosition, during).SetEase(Ease.Linear).OnComplete(() =>
            {
                if (callback != null)
                    callback();
            });
        }
        if (RoleInSuperMarketCtrl.Instance.isFollowCam && !MarketMainSceneCtrl.Instance.isShakeCar)
        {
            //使人物跟随摄像机移动
            if (targetPosition < RoleInSuperMarketCtrl.Instance.transform.position.x)
                RoleRotate = Mathf.Abs(roleObject.transform.localScale.z);
            else if (targetPosition > RoleInSuperMarketCtrl.Instance.transform.position.x)
                RoleRotate = Mathf.Abs(roleObject.transform.localScale.z) * -1;
            RoleInSuperMarketCtrl.Instance.RotateRole(RoleRotate);
            SetRoleAnim(4);
            //if (during != 0.3f) during += 1f;
            RoleInSuperMarketCtrl.Instance.transform.DOMoveX(targetPosition, during).SetEase(Ease.Linear).OnComplete(() =>
            {
                SetRoleAnim(3);
                //RoleRotate = Mathf.Abs(roleObject.transform.localScale.z);
                //RoleInSuperMarketCtrl.Instance.RotateRole(RoleRotate);
            });//RoleFollow(true, superCamera.transform.position.x, roleRotate, smoothing);
        }
    }


    public void SetLediAnim(string name)
    {
        lediAnim.CrossFade(name, 0.2f);
    }

    public bool GetLediAnimIsTalk()
    {
        AnimatorStateInfo info = lediAnim.GetCurrentAnimatorStateInfo(0);
        Debug.Log(info.IsName("TalkBegin").ToString() + "  === TalkBegin ");
        return info.IsName("TalkBegin");//|| info.IsName("Talk") || info.IsName("TalkEnd");
    }

    public void CloseTheDoor()
    {
        MarketMainSceneCtrl.Instance.CloseTheDoor();
    }

    public void OpenShoppingView()
    {
        ShoppingListController.Instance.OpenView();
    }

    public void CarShakeEnabel(bool isEnabel)
    {
        if (isEnabel)
            MarketMainSceneCtrl.Instance.ShakeShopCar();
        MarketMainSceneCtrl.Instance.isShakeCar = isEnabel;
    }

    public void DragScceneEnable(bool isEnabel)
    {
        //Debug.LogError("  DragScceneEnable ===== " + isEnabel.ToString());
        isCanDragScene = isEnabel;
    }
    public void ShowShopCar()
    {
        if (shoppingCar != null)
        {
            RoleInSuperMarketCtrl.Instance.transform.DORotate(new Vector3(0, -90, 0), 0.5f).OnComplete(() =>
            {
                shoppingCar.SetActive(true);
                RoleInSuperMarketCtrl.Instance.WalkInCenter();
            });
        }
    }
    public void InitCarPoints(Transform _shoppingCar)
    {
        shoppingCar = _shoppingCar;
        downPoint = shoppingCar.Find("downPoint");
        putPoint = shoppingCar.Find("putPoint");
        /*putPoint1 = shoppingCar.Find("putPoint1");
        putPoint2 = shoppingCar.Find("putPoint2");
        putPoint3 = shoppingCar.Find("putPoint3");*/
    }

    public void AddCarPointRotate(int index)
    {
        Debug.Log(index + "  == ,localEulerAngles ===  " + shoppingCar.localEulerAngles.y);
        if (!putPointCarRotateDic.ContainsKey(index))
            putPointCarRotateDic.Add(index, roleObject.transform.localScale.z);
    }
    /// <summary>
    /// 检查人物左右旋转时商品的旋转（否则面片看不到） ==== 弃用  
    /// </summary>
    public void CheckGoodsRotate(float nowAngle)
    {/*
        int index = putPoint1.childCount + putPoint2.childCount + putPoint3.childCount;
        Transform[] tempTrans = { putPoint1, putPoint2, putPoint3 };
        for (int i = 0; i < index; i++)
        {
            if (putPointCarRotateDic[i] != nowAngle)
            {
                float angle = tempTrans[i].localScale.z == 1 ? -1 : 1;
                tempTrans[i].localScale = new Vector3(tempTrans[i].localScale.x, tempTrans[i].localScale.y, angle);
                putPointCarRotateDic[i] = nowAngle;
            }
        }*/
    }

    public void SetRoleAnim(int value, System.Action action = null)
    {
        RoleInSuperMarketCtrl.Instance.SetRoleAnim(value, action);
    }

    public void WayPointEnable(bool Enable)
    {
        ShoppingListController.Instance.WayPointEnable(Enable);
    }

    public void SetRolePosition(Vector3 position)
    {
        if (roleObject != null)
        {
            roleObject.transform.position = position;
            roleObject.transform.rotation = Quaternion.identity;
            roleObject.transform.localScale = new Vector3(roleObject.transform.localScale.x, roleObject.transform.localScale.y, roleObject.transform.localScale.x);
        }
    }

    public float TotalPrice(string name)
    {
        return PlaceGoods.Instance.TotalPrice(name);
    }

    public void CloseShopView()
    {
        ShoppingListController.Instance.CloseView();
    }

    /// <summary>
    /// 从扫描台扫描的物品放回购物车（人物出门需要使用）
    /// </summary>
    /// <param name="goods"></param>
    /// <param name="index"></param>
    public void PutGoodsBackShopCar(Transform goods, int index)
    {
        /*switch (index)
        {
            case 1:
                goods.SetParent(putPoint1);
                break;
            case 2:
                goods.SetParent(putPoint2);
                break;
            case 3:
                goods.SetParent(putPoint3);
                break;
        }*/
        goods.localPosition = Vector3.zero;
    }

    /// <summary>
    /// 购物完成切换扫码台
    /// </summary>
    public void SwitchScanCode()
    {
        //TODO 播放胜利效果  ， 切换扫码
        //MarketMainSceneCtrl.Instance.PlaySuccessEffect(true, roleObject.transform.position);
        Debug.Log("SwitchScanCode ====== ");
        StartCoroutine(TimeUtility.DelayInvoke(0.3f, () =>
        {
            AudioManager.Instance.StopSound(AudioManager.Instance.GetAudioClip(SuperMarketResPath.Sound_603010706));
            MarketMainSceneCtrl.Instance.PlaySuccessEffect(false, Vector3.zero);

            TransitionManager.Instance.StartTransition(() =>
            {
                roleObject.transform.localRotation = Quaternion.identity;
                SetRoleAnim(0);
            },
                () =>
                {
                    SuperMarketGame.Instance.CloseShopView();
                    SetRolePosition(new Vector3(-5.72f, 0f, -0.38f));
                    superCamera.transform.position = shaomaCamera.transform.position;
                    superCamera.transform.rotation = shaomaCamera.transform.rotation;
                    if (scanCodeObject == null)
                    {
                        scanCodeObject = GameObject.Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.ShaoMaObject));
                        scanCodeObject.transform.position = Vector3.zero;
                        scanCodeObject.transform.localScale = Vector3.one;
                        scanCodeObject.transform.rotation = Quaternion.identity;
                    }
                    else
                    {
                        scanCodeObject.SetActive(true);
                    }
                    RoleInSuperMarketCtrl.Instance.ResetCarPos();
                    shoppingCar.SetActive(false);
                    ScanCodeController sc = scanCodeObject.GetComponent<ScanCodeController>();
                    if (sc == null)
                        sc = scanCodeObject.AddComponent<ScanCodeController>();
                    List<Transform> tempList = new List<Transform>();
                    for (int i = 0; i < putPoint.childCount; i++)
                    {
                        Transform transTemp = putPoint.GetChild(i);
                        GameObject objTemp = Instantiate(transTemp.gameObject);
                        objTemp.name = transTemp.name;
                        tempList.Add(objTemp.transform);
                    }
                    /*tempList.Add(putPoint1.GetChild(0));
                    tempList.Add(putPoint2.GetChild(0));
                    tempList.Add(putPoint3.GetChild(0));*/
                    sc.Init(tempList);
                },
                TransitionType.Logo);

        }));
    }

    /// <summary>
    ///  扫码台切换到收银台
    /// </summary>
    public void SwitchSettlement(float totalPrice)
    {
        //Debug.Log(" === 找零钱结算 === " + totalPrice);
        ScanPriceController.Instance.ViewSet(false);
        superCamera.transform.position = shouyinCamera.transform.position;
        superCamera.transform.rotation = shouyinCamera.transform.rotation;
        superCamera.fieldOfView = 26;
        if (cashRegisterObject == null)
        {
            cashRegisterObject = GameObject.Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.ShouYinObject));
            cashRegisterObject.transform.position = Vector3.zero;
            cashRegisterObject.transform.localScale = Vector3.one;
            cashRegisterObject.transform.rotation = Quaternion.identity;
        }
        else
        {
            cashRegisterObject.SetActive(true);
        }
        CashRegisterController cr = cashRegisterObject.GetComponent<CashRegisterController>();
        if (cr == null)
            cr = cashRegisterObject.AddComponent<CashRegisterController>();
        cr.Init(totalPrice);
    }
    /// <summary>
    /// 从收银台切换到扫码台
    /// </summary>
    public void SwitchScanFromCash()
    {
        //TODO 1 摄像机  2 出账单
        superCamera.transform.position = shaomaCamera.transform.position;
        superCamera.transform.rotation = shaomaCamera.transform.rotation;
        superCamera.fieldOfView = 18;
        ScanPriceController.Instance.ViewSet(true);
        scanCodeObject.GetComponent<ScanCodeController>().Billing();
    }

    /// <summary>
    /// 切到主场景 购物离开,初始化，下一个到来
    /// </summary>
    public void OnEndGame()
    {
        //TODO 
        /*
        1、画面转场主场景，角色拎着一包商品站在门口。乐迪跟客人道别。
            乐迪（开心的）：“购物愉快，再见。”
        2、超市门开，角色拎着购物袋出门，向右侧走去。门自动关闭。
            角色离开后等待2 - 3秒，其他角色随机到来。游戏重复。
        */
        //guidHand = true;
        //guidWay = true;
        isFirstPlay = false;
        superCamera.transform.position = orgMainCamPos;
        superCamera.transform.rotation = orgMainCamRota;
        shopPanelOpenTime = 5f;
        SetLediAnim("inspire_ledi_01");
        shoppingCar.SetActive(true);
        roleObject.transform.position = new Vector3(1.32f, 0, 0.5f);
        roleObject.transform.rotation = Quaternion.Euler(new Vector3(0, 180f, 0));
        SetRoleAnim(3);

        int ranSound = Random.Range(0, 3);
        string soundPath = SuperMarketResPath.Sound_404050407;
        if (ranSound == 0)
            soundPath = SuperMarketResPath.Sound_404050407;
        else if (ranSound == 1)
            soundPath = SuperMarketResPath.Sound_404050408;
        else if (ranSound == 2)
            soundPath = SuperMarketResPath.Sound_404050202;
        soundCtrl.PlayLeDiVoiceAnimation(soundPath, () =>
        {
            soundCtrl.PlayRoleSound(RoleSoundType.LediBye);

            SetRoleAnim(4);
            roleObject.transform.DOMoveZ(-1f, 2f).OnComplete(() =>
            {
                SetRoleAnim(3);
                TweenCallback callback = () =>
                {
                    SetRoleAnim(4);
                    roleObject.transform.DOMoveZ(-6f, 3.5f).OnComplete(() =>
                    {
                        SetRoleAnim(3);
                        roleObject.transform.DORotate(new Vector3(0, -90, 0), 0.3f).OnComplete(() =>
                        {
                            SetRoleAnim(4);
                            MarketMainSceneCtrl.Instance.CloseTheDoor();
                            roleObject.transform.DOMoveX(0.5f, 0.5f).OnComplete(() =>
                            {
                                //shoppingCar.SetActive(false);

                                Destroy(roleObject);
                                StartCoroutine(TimeUtility.DelayInvoke(1f, () =>
                                {
                                    OnReset(TransitionType.Logo);
                                }));
                                //Invoke("OnReset", 3f);
                            });
                        });
                    });
                };
                MarketMainSceneCtrl.Instance.OpenTheDoor(callback);
            });
        });

    }

    /// <summary>
    ///  重置游戏
    /// </summary>
    /// <param name="type">类型</param>
    /// <param name="startAct">回调</param>
    public void OnReset(TransitionType type, System.Action startAct = null, System.Action endAct = null)
    {
        TransitionManager.Instance.StartTransition(startAct, () =>
        {
            if (endAct != null)
                endAct();
            gameCount++;
            InitGameObject();
        }, type);
    }

    protected override void OnDestroy()
    {
        gameCount = 0;
        CurRoleType = 0;
        //ScanPriceController.Instance.CloseView();
        //ShoppingListController.Instance.CloseView();
        StopAllCoroutines();
        base.OnDestroy();
    }
}
